package net.jarang.study.spring.web;

import java.nio.charset.Charset;

import net.jarang.study.spring.annotation.User;
import net.jarang.study.spring.board.VisitBO;
import net.jarang.study.spring.converter.Level;
import net.jarang.study.spring.converter.LevelPropertyEditor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ValidationController {	
	@Autowired VisitBO visitBO;

	@RequestMapping("/typefail1")
	public ModelAndView typefail1(@RequestParam int age) {
		ModelAndView mav = new ModelAndView("result");
		mav.addObject("result1", age);
		return mav;
	}
	
	@RequestMapping("/typefail2")
	public ModelAndView typefail2(@ModelAttribute User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			System.out.println(bindingResult.getAllErrors().get(0));
		}
		ModelAndView mav = new ModelAndView("result");
		mav.addObject("result1", user.getAge());
		mav.addObject("result2", user.getName());
		return mav;
	}

	@RequestMapping("/charset1")
	public ModelAndView charset1(@RequestParam Charset charset) {
		ModelAndView mav = new ModelAndView("result");
		mav.addObject("result1", charset);
		return mav;
	}
	
	@RequestMapping("/level1")
	public ModelAndView level1(@RequestParam Level level) {
		ModelAndView mav = new ModelAndView("result");
		mav.addObject("result1", level);
		return mav;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Level.class, new LevelPropertyEditor());
	}
}
